import { useCallback, useEffect, useState } from 'react';
import { useEvent } from 'expo';
import { requireNativeModule } from 'expo-modules-core';
import ExpoDlnaPlayer, { DeviceInfo, PlaybackStatus, AirPlayButton } from 'expo-dlna-player';
import { Button, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, View, FlatList, Alert, Switch, Platform, TouchableOpacity } from 'react-native';

// 辅助函数：检查设备是否支持完整DLNA功能
const hasDLNAControlCapability = (device: any): boolean => {
  // 检查设备是否有controlURL和其他必要DLNA参数
  return (
    device && 
    device.type === 'dlna' && 
    device.controlURL && 
    device.controlURL.length > 0
  );
};

// 辅助函数：获取设备显示名称
const getDeviceDisplayName = (device: DeviceInfo): string => {
  if (!device) return '未知设备';
  
  let name = device.name || '未命名设备';
  if (device.model) {
    name += ` (${device.model})`;
  }
  return name;
};

// 平台是否为iOS
const isIOS = Platform.OS === 'ios';

export default function App() {
  const [devices, setDevices] = useState<DeviceInfo[]>([]);
  const [connectedDevice, setConnectedDevice] = useState<DeviceInfo | null>(null);
  const [mediaUrl, setMediaUrl] = useState('https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4');
  const [status, setStatus] = useState<PlaybackStatus | null>(null);
  const [isDiscovering, setIsDiscovering] = useState(false);
  const [projectionSupported, setProjectionSupported] = useState(false);
  const [isScreenMode, setIsScreenMode] = useState(true);
  const [showDeviceList, setShowDeviceList] = useState(false); // 控制Android设备列表显示

  const dlnaModule = requireNativeModule('ExpoDlnaPlayer');

  // 监听事件
  const onDeviceFound = useEvent(dlnaModule, 'onDeviceFound');
  const onDeviceDisappeared = useEvent(dlnaModule, 'onDeviceDisappeared');
  const onConnectionChanged = useEvent(dlnaModule, 'onConnectionChanged');
  const onPlaybackStatusChanged = useEvent(dlnaModule, 'onPlaybackStatusChanged');
  const onError = useEvent(dlnaModule, 'onError');
  const onPermissionStatus = useEvent(dlnaModule, 'onPermissionStatus');

  // 检查Miracast支持
  useEffect(() => {
    if (Platform.OS === 'android') {
      const checkProjectionSupport = async () => {
        try {
          const supported = await dlnaModule.isProjectionSupported();
          setProjectionSupported(supported);
        } catch (error) {
          console.error("检查投屏支持失败:", error);
        }
      };
      checkProjectionSupport();
    }
  }, []);

  // 处理设备发现
  useEffect(() => {
    if (onDeviceFound) {
      const device = onDeviceFound as DeviceInfo;
      if (device && device.id) {
        console.log("发现设备:", {
          id: device.id,
          name: device.name,
          type: device.type,
          model: device.model,
          controlURL: device.controlURL || '未定义'
        });
        
        setDevices(prev => {
          // 检查设备是否已存在
          const existingDeviceIndex = prev.findIndex(d => d?.id === device.id);
          
          if (existingDeviceIndex >= 0) {
            // 如果设备已存在，更新设备信息
            const updatedDevices = [...prev];
            updatedDevices[existingDeviceIndex] = device;
            return updatedDevices;
          } else {
            // 如果设备不存在，追加到列表
            return [...prev, device];
          }
        });
      }
    }
  }, [onDeviceFound]);

  // 处理设备消失
  useEffect(() => {
    if (onDeviceDisappeared) {
      const deviceId = (onDeviceDisappeared as any).deviceId as string;
      if (deviceId) {
        console.log("设备已消失:", deviceId);
        
        setDevices(prev => prev.filter(d => d?.id !== deviceId));
        
        // 如果消失的设备是当前连接的设备，清除连接状态
        if (connectedDevice?.id === deviceId) {
          setConnectedDevice(null);
        }
      }
    }
  }, [onDeviceDisappeared, connectedDevice]);

  // 处理连接状态变化
  useEffect(() => {
    if (onConnectionChanged) {
      const { deviceId, connected } = (onConnectionChanged as any);
      console.log("连接状态变化:", deviceId, connected ? "已连接" : "已断开");
      
      if (connected && deviceId) {
        const device = devices.find(d => d?.id === deviceId);
        if (device) {
          setConnectedDevice(device);
        }
      } else {
        setConnectedDevice(null);
      }
    }
  }, [onConnectionChanged, devices]);

  // 处理播放状态变化
  useEffect(() => {
    if (onPlaybackStatusChanged) {
      setStatus(onPlaybackStatusChanged as PlaybackStatus);
    }
  }, [onPlaybackStatusChanged]);

  // 处理错误
  useEffect(() => {
    if (onError) {
      const { code, message } = (onError as any);
      Alert.alert('错误', `${code}: ${message}`);
    }
  }, [onError]);

  // 处理权限状态
  useEffect(() => {
    if (onPermissionStatus) {
      const { permission, status } = (onPermissionStatus as any);
      console.log(`权限状态: ${permission} - ${status}`);
      
      if (status === 'denied') {
        Alert.alert(
          '权限被拒绝',
          `${permission === 'localNetwork' ? '本地网络' : permission}权限被拒绝，这可能会影响投屏功能`,
          [
            { text: '关闭', style: 'cancel' }
          ]
        );
      }
    }
  }, [onPermissionStatus]);

  // 加载设备列表
  const loadDevices = useCallback(async () => {
    try {
      const deviceList = await dlnaModule.getDevices();
      console.log("加载设备列表:", deviceList.length);
      setDevices(deviceList);
    } catch (error: any) {
      console.error("加载设备列表失败:", error);
    }
  }, []);

  // 开始设备搜索
  const startDiscovery = useCallback(async () => {
    try {
      setIsDiscovering(true);
      await dlnaModule.startDiscovery();
      
      if (!isIOS) {
        // Android平台，显示设备列表
        setShowDeviceList(true);
      }
      
      console.log("已开始搜索设备");
    } catch (error) {
      console.error("搜索设备失败:", error);
      setIsDiscovering(false);
    }
  }, []);

  // 停止设备搜索
  const stopDiscovery = useCallback(async () => {
    try {
      await dlnaModule.stopDiscovery();
      setIsDiscovering(false);
      if (!isIOS) {
        setShowDeviceList(false);
      }
    } catch (error) {
      console.error(error);
    }
  }, []);

  // 刷新设备列表
  const refreshDevices = useCallback(async () => {
    if (isIOS) {
      // iOS直接调用startDiscovery触发系统AirPlay选择器
      await startDiscovery();
    } else {
      // Android刷新设备列表
      await loadDevices();
    }
  }, [loadDevices, startDiscovery]);

  // 连接到设备
  const connectToDevice = useCallback(async (deviceId: string) => {
    try {
      const device = devices.find(d => d.id === deviceId);
      if (!device) {
        Alert.alert('错误', '找不到指定设备');
        return;
      }
      
      console.log("正在连接设备:", device.name);

      if (device.type === 'miracast' && projectionSupported) {
        const mode = isScreenMode ? 'SCREEN_MIRRORING' : 'VIDEO_ONLY';
        console.log("使用Miracast协议连接，模式:", mode);
        const result = await dlnaModule.startProjection(deviceId, mode);
        if (result) {
          setConnectedDevice(device);
        } else {
          Alert.alert('错误', '连接Miracast设备失败');
        }
      } else {
        console.log("使用DLNA/AirPlay协议连接设备");
        try {
          const result = await dlnaModule.connectToDevice(deviceId);
          if (result) {
            const connectedDevice = await dlnaModule.getConnectedDevice();
            setConnectedDevice(connectedDevice);
          } else {
            Alert.alert('错误', '连接设备失败');
          }
        } catch (error: any) {
          console.error("DLNA/AirPlay连接错误:", error);
          Alert.alert('连接错误', `${error.message || '未知错误'}`);
        }
      }
    } catch (error: any) {
      console.error("连接设备失败:", error);
      Alert.alert('连接错误', `${error.message || '未知错误'}`);
    }
  }, [devices, projectionSupported, isScreenMode]);

  // 断开连接
  const disconnect = useCallback(async () => {
    try {
      if (!connectedDevice) return;
      
      if (connectedDevice.type === 'miracast') {
        await dlnaModule.stopProjection();
      } else {
        await dlnaModule.disconnectFromDevice();
      }
      
      setConnectedDevice(null);
    } catch (error) {
      console.error(error);
    }
  }, [connectedDevice]);

  // 播放媒体
  const playMedia = useCallback(async () => {
    try {
      if (!mediaUrl) {
        Alert.alert('错误', '请输入媒体URL');
        return;
      }
      
      if (!connectedDevice && !isIOS) {
        Alert.alert('错误', '请先连接到设备');
        return;
      }
      
      // iOS可能不需要明确连接设备，只要用户通过系统UI选择了AirPlay设备
      if (connectedDevice?.type !== 'miracast') {
        await dlnaModule.play(mediaUrl);
        console.log("正在播放媒体:", mediaUrl);
      }
    } catch (error: any) {
      console.error("播放失败:", error);
      Alert.alert('播放错误', error.message || '未知错误');
    }
  }, [mediaUrl, connectedDevice]);

  // 组件卸载时停止搜索和断开连接
  useEffect(() => {
    return () => {
      dlnaModule.stopDiscovery().catch(console.error);
      if (connectedDevice) {
        if (connectedDevice.type === 'miracast') {
          dlnaModule.stopProjection().catch(console.error);
        } else {
          dlnaModule.disconnectFromDevice().catch(console.error);
        }
      }
    };
  }, [connectedDevice]);

  // 格式化时间
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
  };

  // 渲染设备列表项
  const renderDeviceItem = ({ item }: { item: DeviceInfo }) => {
    if (!item) return null;
    
    const isConnected = connectedDevice?.id === item.id;
    const isMiracast = item.type === 'miracast';
    const isDLNA = item.type === 'dlna';
    const hasControl = hasDLNAControlCapability(item);
    
    return (
      <View style={styles.deviceItem}>
        <View style={styles.deviceInfo}>
          <Text style={styles.deviceName}>{item.name || '未知设备'}</Text>
          <Text style={styles.deviceModel}>
            {item.model || ''} - {isMiracast ? '无线显示' : (isDLNA ? 'DLNA设备' : 'AirPlay设备')} 
            <Text style={{fontWeight: 'bold'}}> ({item.type})</Text>
          </Text>
          {isDLNA && (
            <Text style={{fontSize: 10, color: hasControl ? 'green' : 'red'}}>
              {hasControl ? '支持DLNA控制' : '可能不支持DLNA控制'}
            </Text>
          )}
        </View>
        <Button
          title={isConnected ? "已连接" : (isMiracast ? "投屏" : "连接")}
          disabled={isConnected}
          onPress={() => connectToDevice(item.id)}
        />
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView style={styles.scrollView}>
        <Text style={styles.header}>DLNA/AirPlay/Miracast 投屏示例</Text>
        
        {/* 媒体URL输入 */}
        <Group name="媒体URL">
          <TextInput
            style={styles.input}
            value={mediaUrl}
            onChangeText={setMediaUrl}
            placeholder="输入媒体URL"
            autoCapitalize="none"
          />
        </Group>
        
        {/* 平台特定的投屏控件 */}
        <Group name="投屏控制">
          {isIOS ? (
            /* iOS - 显示原生AirPlay按钮 */
            <View style={styles.iosContainer}>
              <Text style={styles.airplayText}>点击下方按钮选择AirPlay设备：</Text>
              <View style={styles.airplayButtonContainer}>
                <AirPlayButton 
                  style={styles.airplayButtonNative}
                  activeTintColor="#007AFF" 
                  tintColor="#8E8E93"
                  prioritizesVideoDevices={true}
                  onRouteChange={(event) => {
                    // 监听路由变化事件
                    console.log('AirPlay路由变化:', event);
                    if (event.isAirPlayActive) {
                      console.log('已连接到AirPlay设备');
                    }
                  }}
                />
              </View>
              <View style={styles.buttonRow}>
                <Button
                  title="播放媒体"
                  onPress={playMedia}
                />
                {connectedDevice && (
                  <Button
                    title="断开连接"
                    onPress={disconnect}
                  />
                )}
              </View>
            </View>
          ) : (
            /* Android - 显示设备搜索和列表 */
            <View>
              <View style={styles.buttonRow}>
                <Button
                  title={isDiscovering ? "停止搜索" : "开始搜索"}
                  onPress={isDiscovering ? stopDiscovery : startDiscovery}
                />
                <Button
                  title="刷新列表"
                  onPress={refreshDevices}
                  disabled={devices.length === 0}
                />
              </View>
              
              {projectionSupported && (
                <View style={styles.switchContainer}>
                  <Text>Miracast投屏模式:</Text>
                  <View style={styles.switchRow}>
                    <Text>视频</Text>
                    <Switch
                      value={isScreenMode}
                      onValueChange={setIsScreenMode}
                    />
                    <Text>屏幕</Text>
                  </View>
                </View>
              )}
              
              {devices.length > 0 ? (
                <FlatList
                  data={devices}
                  renderItem={renderDeviceItem}
                  keyExtractor={(item) => item.id}
                  style={styles.deviceList}
                />
              ) : (
                <Text style={styles.emptyListText}>
                  {isDiscovering ? "正在搜索设备..." : "没有发现设备"}
                </Text>
              )}
              
              {connectedDevice && (
                <View style={styles.connectedDeviceContainer}>
                  <Text style={styles.connectedDeviceText}>
                    已连接: {getDeviceDisplayName(connectedDevice)}
                  </Text>
                  <Button title="断开连接" onPress={disconnect} />
                  <Button title="播放媒体" onPress={playMedia} />
                </View>
              )}
            </View>
          )}
        </Group>
        
        {/* 播放状态显示 */}
        {status && (
          <Group name="播放状态">
            <View style={styles.statusContainer}>
              <Text>状态: {status.isPlaying ? '播放中' : '已暂停'}</Text>
              <Text>位置: {formatTime(status.position)} / {formatTime(status.duration)}</Text>
              <Text>音量: {Math.round(status.volume)}%</Text>
              <View style={styles.buttonRow}>
                <Button 
                  title="暂停"
                  onPress={() => dlnaModule.pause()}
                  disabled={!status.isPlaying}
                />
                <Button
                  title="继续"
                  onPress={() => dlnaModule.resume()}
                  disabled={status.isPlaying}
                />
                <Button
                  title="停止"
                  onPress={() => dlnaModule.stop()}
                />
              </View>
            </View>
          </Group>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

// Helper component for grouping content
const Group = ({ name, children }: { name: string, children: React.ReactNode }) => (
  <View style={styles.group}>
    <Text style={styles.groupHeader}>{name}</Text>
    <View style={styles.groupContent}>
      {children}
    </View>
  </View>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  scrollView: {
    flex: 1,
    padding: 16,
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
  },
  group: {
    marginBottom: 20,
    backgroundColor: '#fff',
    borderRadius: 8,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 1.5,
    elevation: 2,
  },
  groupHeader: {
    backgroundColor: '#f0f0f0',
    paddingVertical: 10,
    paddingHorizontal: 16,
    fontWeight: 'bold',
  },
  groupContent: {
    padding: 16,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 4,
    padding: 8,
    marginBottom: 8,
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 8,
  },
  deviceList: {
    marginTop: 8,
  },
  deviceItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  deviceInfo: {
    flex: 1,
  },
  deviceName: {
    fontWeight: 'bold',
    fontSize: 16,
  },
  deviceModel: {
    fontSize: 12,
    color: '#666',
  },
  emptyListText: {
    textAlign: 'center',
    marginTop: 20,
    marginBottom: 20,
    color: '#666',
    fontStyle: 'italic',
  },
  connectedDeviceContainer: {
    marginTop: 16,
    padding: 12,
    backgroundColor: '#e8f5e9',
    borderRadius: 8,
    alignItems: 'center',
  },
  connectedDeviceText: {
    fontWeight: 'bold',
    marginBottom: 8,
  },
  statusContainer: {
    padding: 8,
  },
  switchContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginVertical: 10,
  },
  switchRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  iosContainer: {
    alignItems: 'center',
    padding: 16,
  },
  airplayText: {
    marginBottom: 16,
    fontSize: 16,
  },
  airplayButtonContainer: {
    marginBottom: 24,
    backgroundColor: '#f0f0f0',
    borderRadius: 10,
    padding: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  airplayButtonNative: {
    width: 60,
    height: 60,
  },
});
